<?php
/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * For more information, see <http://www.aljey.com>.
 */

namespace Al\Core\Lib\CacheDriver;

use Al\Core\Lib\ParameterHolder;

/**
 * Provides file-based persistent storage through a highly convenient array-like
 * interface.
 *
 * @author Eugene Kuzmenko <mail@aljey.com>
 */
class FileCache extends ParameterHolder {
  
  /**
   * @var string A path to the cache directory.
   */
  private $cache_dir = '../app/cache';

  /**
   * @var bool Has any of the values in the cache been modified/removed.
   */
  private $modified = false;
  
  /**
   * {@inheritDoc}
   */
  public function __construct() {
    @mkdir($this->cache_dir, 0777, true);
    $data = @include_once "$this->cache_dir/file_cache.php";
    parent::__construct(is_array($data) ? $data : array());
  }

  /**
   * {@inheritDoc}
   */
  public function offsetSet($offset, $value) {
    if (is_null($offset) || !isset($this[$offset]) ||
        ($this[$offset] !== $value)) {
      $this->modified = true;
    }
    parent::offsetSet($offset, $value);
  }

  /**
   * {@inheritDoc}
   */
  public function offsetUnset($offset) {
    parent::offsetUnset($offset);
    $this->modified = true;
  }

  /**
   * If the data in cache has been modified saves the changes to disk.
   */
  public function __destruct() {
    if ($this->modified) {
      if (ROOT_DIR !== getcwd()) {
        chdir(ROOT_DIR);
      }
      file_put_contents("$this->cache_dir/file_cache.php", "<?php\nreturn " .
        var_export($this->data, true) . ';');
    }
  }
  
}